<template>
  <div class="home-container">
    <div class="swiper-box" placeholder>
      <!-- 首页轮播图 -->
      <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
        <van-swipe-item><img src="../../../../public/static/img/MXBC.jpeg" alt=""></van-swipe-item>
        <van-swipe-item><img src="../../../../public/static/img/SeafoodCasserole.jpeg" alt="">
        </van-swipe-item>
        <van-swipe-item><img src="../../../../public/static/img/GoldenTea.jpeg" alt="">
        </van-swipe-item>
      </van-swipe>
      <!-- 首页定位、排序、搜索栏 -->
      <div class="filter-box">
        <div class="place-box" @click="searchCity">
          <div class="iconfont icon-place"></div>
          <span class="current_address">{{positionMode?changePosition.nowAddress:nowPositong.nowAddress}}</span>
        </div>
        <div class="filters">
          <div class="ranking_box">
            <van-dropdown-menu active-color="orange">
              <van-dropdown-item v-model="value" :options="option" />
            </van-dropdown-menu>
          </div>
          <div class="icon_search" @click="closeSearch">
            <span class="iconfont search_shops"></span>
          </div>
        </div>
        <div :class="searchClassName">
          <div class="iconfont closeSearch" @click="closeSearch"></div>
          <input class="searchShops" type="text" :placeholder="$t('m.home.sInfo')" v-model="searchText">
          <a class="searchBtn" href="javascript:;">{{$t('m.home.search')}}</a>
        </div>
      </div>
    </div>

    <!-- 商家列表路由规则 -->
    <div class="shops-list" v-for="item in shopsList" :key="item.id">
      <van-card :desc="item.slogan" :title="item.name" :thumb="item.img" @click="getGoodsLists(item, item.id)">
        <template #tags>
          <van-tag type="warning" v-if="item.config.has_delivery">
            {{$t('m.home.service_1')}}
          </van-tag>
          <van-tag type="success" v-if="item.config.has_pickup">
            {{$t('m.home.service_2')}}
          </van-tag>
          <van-tag round type="primary">
            {{item.distance > 1 ? item.distance + 'km' : item.distance*10 + '00' + 'm'}}</van-tag>
        </template>
      </van-card>
    </div>
    <!-- </router-link> -->
  </div>
</template>
<script src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js"></script>
<script>
import { mapState } from 'vuex'
import axios from 'axios'

export default {
  data() {
    return {
      value: 'a',
      positionMode: false,
      option: [
        { text: this.$t('m.home.sort.def'), value: 'a' },
        { text: this.$t('m.home.sort.good'), value: 'b' },
        { text: this.$t('m.home.sort.distance'), value: 'c' }
      ],
      searchClassName: 'searchShops-box-close',
      searchText: ''
    }
  },
  // 自动初始化 Vuex 商家列表、定位
  created() {
    this.$store.dispatch('getShopList')
    this.positionMode = this.$store.state.positionMode
    if (this.positionMode === false) {
      setTimeout(() => {
        this.initPosition()
      }, 600)
    }
  },
  // 访问 Vuex 商家列表、定位数据
  computed: {
    ...mapState(['shopsList', 'nowPositong', 'changePosition'])
  },
  methods: {
    // 首页手动定位页面路由规则
    searchCity() {
      this.$router.push('/home/position')
    },
    // 首页初始化定位
    initPosition() {
      var _that = this
      AMap.plugin('AMap.Geolocation', function () {
        var geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: true,
          // 设置定位超时时间，默认：无穷大
          timeout: 10000
        })
        geolocation.getCurrentPosition(function (status, result) {
          if (status === 'complete') {
            _that.lng = result.position.lng.toString()
            _that.lat = result.position.lat.toString()
            _that.getAddress((_that.lng + ',' + _that.lat).toString())
          } else {
            // console.log('定位失败')
          }
        })
      })
    },
    // 根据坐标返回地址(逆地理编码，获取详细地址)
    getAddress(data) {
      axios({
        method: 'GET',
        url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
        params: {
          key: '8857783cc0db9ee595f99da7893d2e56',
          location: data
        }
      }).then(result => {
        if (result.status === 200) {
          var address = result.data.regeocode.formatted_address
          var addressComponent = result.data.regeocode.addressComponent
          this.$store.commit('initPosition', { nowAddress: address, detailInfo: addressComponent, position: data })
        } else {
          this.$store.commit('initPosition', { nowAddress: '定位失败,请刷新重试' })
        }
      })
    },
    // 打开、关闭商家搜索框
    closeSearch() {
      this.searchClassName = this.searchClassName === 'searchShops-box' ? 'searchShops-box-close' : 'searchShops-box'
      this.searchText = ''
    },
    // 使用当前商店 JSON 文件名和 id 用于存储请求到的数据
    async getGoodsLists(item, id) {
      const { data: res } = await axios.get('/static/' + item.filename + '.json')
      if (item.filename === 'milktea') {
        const { data: list } = await axios.get('/static/' + item.filename + 'item' + '.json')
        const { data: config } = await axios.get('/static/' + item.filename + 'config' + '.json')
        res.category.find((a, i) => {
          a.item_id = a.id
          a.type = a.name
          var arr = []
          list.item.find((b, k) => {
            if (a.id === b.category_id) {
              b.amount = 0
              arr.push(b)
            }
          })
          res.category[i].goodsinfo = arr
        })
        sessionStorage.setItem('saveGoodsList', JSON.stringify({ shop_id: id, goods_list: res.category, shop_config: config }))
      } else {
        for (let i = 0; i < res.length; i++) {
          for (let k = 0; k < res[i].goodsinfo.length; k++) {
            res[i].goodsinfo[k].amount = 0
          }
        }
        sessionStorage.setItem('saveGoodsList', JSON.stringify({ shop_id: id, goods_list: res }))
      }

      sessionStorage.setItem('saveNowShop', JSON.stringify(item))
      this.$emit('getID', id)
      this.$router.push('/home/goodspage/' + id)
    }
  }
}
</script>

<style lang="less">
.home-container {
  display: flex;
  flex-direction: column;
  max-width: 640px;
  max-height: 100%;
  width: 100%;
  height: 100%;
  margin: auto;
}
.shops-list {
  position: relative;
  display: flex;
  align-items: center;
  width: 97%;
  height: 120px;
  top: 265px;
  margin-top: 6px;
  border-radius: 9px;
  background: white;
  box-shadow: 0px 0px 5px -3px black;
  .van-card {
    width: 100%;
    border-radius: 9px;
    background: white;
    .van-card__header {
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .van-card__title {
      height: 20px;
      font-size: 20px;
      line-height: 20px;
    }
    .van-card__desc {
      font-size: 14px;
    }
    .van-tag--warning {
      position: relative;
      top: 2.7em;
      margin-right: 3px;
    }
    .van-tag--success {
      position: relative;
      top: 2.7em;
      margin-right: 3px;
    }
    .van-tag--primary {
      position: absolute;
      bottom: 0;
      right: 0;
    }
  }
}
.swiper-box {
  position: fixed;
  max-width: 640px;
  width: 100%;
  z-index: 1;
  .my-swipe .van-swipe-item {
    height: 220px;
    color: #fff;
    font-size: 20px;
    line-height: 200px;
    text-align: center;
    background-color: #39a9ed;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .filter-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: white;
    height: 45px;
    box-shadow: 0px 0px 6px -3px;
    .filters {
      display: flex;
      align-items: center;
      .van-dropdown-menu__bar {
        height: 45px;
        box-shadow: none;
        .van-ellipsis {
          color: orange;
          font-size: 1em;
        }
      }
      .ranking_box {
        .van-popup {
          position: relative;
          max-width: 640px;
          margin: auto;
        }
      }
    }
    .icon_search {
      width: 45px;
      text-align: center;
      .search_shops:before {
        content: '\e603';
        font-size: 1.2em;
        color: orange;
      }
    }
    .place-box {
      display: flex;
      align-items: center;
      .icon-place:before {
        content: '\e62f';
        font-size: 1.5em;
        color: orange;
      }
      .icon-place {
        width: 30px;
        text-align: center;
      }
      .current_address {
        width: 10em;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 0.9em;
      }
    }
  }
  .searchShops-box-close {
    position: absolute;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 45px;
    background: white;
    transform: translateX(100%);
    transition: all 0.3s;
    opacity: 0;
  }
  .searchShops-box {
    position: absolute;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 45px;
    background: white;
    transition: all 0.3s;
    .closeSearch:before {
      position: relative;
      content: '\e6ed';
      color: orange;
      left: 15px;
      font-weight: 600;
      font-size: 1.2em;
    }
    .searchShops {
      width: 70%;
      height: 70%;
      border-radius: 6px;
      border: 0.01em solid #d9d9d9;
      text-indent: 6px;
    }
    .searchBtn {
      position: relative;
      color: orange;
      right: 15px;
      font-size: 1em;
    }
  }
}
</style>
